package com.lxx.codegen.mbgplugins;

import java.util.List;
import java.util.Properties;

import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.PluginAdapter;
import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType;
import org.mybatis.generator.api.dom.java.Interface;
import org.mybatis.generator.api.dom.java.JavaVisibility;
import org.mybatis.generator.api.dom.java.Method;
import org.mybatis.generator.api.dom.java.Parameter;
import org.mybatis.generator.api.dom.java.TopLevelClass;
import org.mybatis.generator.api.dom.xml.Attribute;
import org.mybatis.generator.api.dom.xml.Document;
import org.mybatis.generator.api.dom.xml.TextElement;
import org.mybatis.generator.api.dom.xml.XmlElement;

public class BatchInsertPlugin extends PluginAdapter{
	
	@Override
	public void setProperties(Properties properties) {
		super.setProperties(properties);
		System.out.println(properties);
	}

	@Override
	public boolean validate(List<String> warnings) {
		return true;
	}
	
	@Override
	public boolean clientGenerated(Interface interfaze,
			TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
//		Method m = new Method("query");
//		m.setVisibility(JavaVisibility.PUBLIC);
//		m.setReturnType(FullyQualifiedJavaType.getNewListInstance());
//		context.getCommentGenerator().addGeneralMethodComment(m,
//				introspectedTable);
//		interfaze.addMethod(m);
		return true;
	}
	
	@Override
	public boolean sqlMapDocumentGenerated(Document document, IntrospectedTable introspectedTable) {
		
		String tableName = introspectedTable.getAliasedFullyQualifiedTableNameAtRuntime();//数据库表名
		StringBuilder names = new StringBuilder("(");
		StringBuilder values = new StringBuilder();
		String item = "item";
		for(IntrospectedColumn col : introspectedTable.getAllColumns()) {
			if (col.isAutoIncrement()) {
				continue;
			}
			names.append(col.getActualColumnName()).append(", ");
			values.append("#{").append(item).append('.').append(col.getJavaProperty())
				.append("}, ");
		}
		names.delete(names.length() - 2, names.length()).append(")");
		values.delete(values.length() - 2, values.length());
		
		XmlElement parentElement = document.getRootElement();

		// 产生分页语句前半部分
		XmlElement queryElement = new XmlElement("insert");
		queryElement.addAttribute(new Attribute("id", "batchInsert"));
		queryElement.addAttribute(new Attribute("parameterType", "java.util.List"));
		queryElement.addAttribute(new Attribute("useGeneratedKeys", "true"));
		queryElement.addAttribute(new Attribute("keyProperty", "id"));
		
		queryElement.addElement(
				new TextElement(
				"insert into "+tableName + names +"\n values \n"
						+ "    <foreach item=\"item\" index=\"index\" collection=\"list\" separator=\",\">\n"
						+ "      (" + values + ")"
						+ "\n    </foreach>"
				));
		
		parentElement.addElement(queryElement);

		return super.sqlMapDocumentGenerated(document, introspectedTable);
	}
	

}
